package com.sodaopen.study.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sodaopen.study.entity.Media;
import com.sodaopen.study.service.MediaService;
import com.sodaopen.study.utils.UploadHelper;

@RestController
public class UploadController {

    @Value("${web.upload-path}")
    private String filePath;
    
    @Autowired
    private MediaService mediaService;

    @RequestMapping(value = "/upload/temp")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) {
        return UploadHelper.saveFile(file, "temp", filePath);  //保存到临时文件夹
    }
    
    
    @GetMapping(value="/d/{id}") 
    public ResponseEntity<byte[]> download(HttpServletRequest request, @PathVariable(name="id")Integer id,
            Model model) throws Exception{
    	
    	Media media = mediaService.findById(id);
    	
    	if(media == null || !"f".equals(media.getType())) {
    		throw new Exception("未找到文件");
    	}
        
        
        File file = new File(filePath + media.getUrl());
        
        HttpHeaders headers = new HttpHeaders();//http头信息
        
        String downloadFileName = new String(media.getName().getBytes("UTF-8"),"iso-8859-1");//设置编码
        
        headers.setContentDispositionFormData("attachment", downloadFileName);
        
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        
        InputStream is = new FileInputStream(file);
        byte[] body = new byte[is.available()];
        is.read(body);
        return new ResponseEntity<byte[]>(body, headers, HttpStatus.CREATED);
        
    }
    
    
}
